package com.lancoo.answer.helper;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import androidx.lifecycle.LifecycleOwner;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hanvon.HWCloudManager;
import com.ivan.easyphotos.callback.RecogniteCallback;
import com.ivan.easyphotos.models.album.entity.Photo;
import com.lancoo.answer.R;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.hanvon.GeneralText;
import com.lancoo.hanvon.Tool;
import com.lancoo.hanvon.sdk.SDK_GeneralTextLanguage;
import com.rxjava.rxlife.RxLife;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2022/3/22 9:35
 * Description:图片识别处理
 */
public class PictureRecognitionHelper {

    public static void startPictureRecognition(final Context context,final ArrayList<Photo> photos,
                                               final RecogniteCallback callback,final Item item){
        callback.onStart();
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        final long startTime=System.currentTimeMillis();
        if(photos.size()==0){
            callback.onSuccess(photos);
            return;
        }

        List<String> imagePathList = item.getImagePathList();
        if(imagePathList==null){
            Log.e("imgPath","图片重置了");
            item.setImagePathList(new ArrayList<>());
        }
        Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    String urlPath=photos.get(0).compressPath;
                    HWCloudManager hwCloudManagerGeneralText = new HWCloudManager(context,
                            "3e1e4e36-5763-4353-9562-539ddf2bf14d"){
                        @Override
                        public String generateID() {
                            return "GT2021";
                        }
                        @Override
                        public String generalTextLanguage(String isText, String picPath) {// 优化超时时长，原SDK10秒钟太短了
                            String androidKey = Tool.findFieldValueOfHWCloudManager(this, "androidKey");
                            String whitelist = Tool.findFieldValueOfHWCloudManager(this, "whitelist");
                            return SDK_GeneralTextLanguage.GeneralTextDiscern(isText, picPath, androidKey, whitelist);
                        }
                    };
                    String result="";
                    try{
                        result = hwCloudManagerGeneralText.generalTextLanguage("0",urlPath);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    if(result==null){
                        result="";
                    }
                    Log.e("识别结果","内容："+result);
                    GeneralText.Result result1=null;
                    try{
                        result1=new Gson().fromJson(result, GeneralText.Result.class);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    String content="";
                    if(result1!=null){
                        content = result1.get();//识别内容
                    }
                    String imgRecognitionTxt = item.getImgRecognitionTxt();

                    if(!TextUtils.isEmpty(content)){
                        assert result1 != null;
                        result1.appendContend=content;
                        if(!TextUtils.isEmpty(imgRecognitionTxt)){
                            item.setImgRecognitionTxt(imgRecognitionTxt+" "+content);
                        }else{
                            item.setImgRecognitionTxt(content);
                        }
                    }
                    emitter.onNext(content);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as((LifecycleOwner)context))
                .subscribe(result -> {
                    if(result==null){
                        showRecognitionAgainDialog(context,photos,callback,item);
                        return;
                    }
                    if(TextUtils.isEmpty(result)){
                        showRecognitionContentEmptyDialog(context,photos,callback);
                        return;
                    }
                    final long endTime=System.currentTimeMillis();
                    Log.e("识别结果","耗时："+(endTime-startTime));
                    Log.e("识别最终结果",item.getImgRecognitionTxt());
                    callback.onSuccess(photos);
                },error-> showRecognitionAgainDialog(context,photos,callback,item));
    }


    /**
     * 重新识别
     */

    private static void showRecognitionAgainDialog(Context context, ArrayList<Photo> photos,
                                                   final RecogniteCallback callback,final Item item){
        callback.onFailed(photos,"");
        String failContent=context.getString(R.string.ev_recognition_picture_error);
        String cancelStr = context.getString(R.string.ev_cancel);
        String retryStr = context.getString(R.string.ev_retry);
        String kindyStr = context.getString(R.string.ev_kindly_prompt);
        ConfirmDialogHelper.showConfirmDialog(context, 2, kindyStr,
                failContent, retryStr, cancelStr, new ConfirmDialogHelper.ConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        startPictureRecognition(context,photos,callback,item);
                    }

                    @Override
                    public void onCancel() {
                        super.onCancel();
                        callback.onSuccess(photos);

                    }
                });
    }
    private static void showRecognitionContentEmptyDialog(Context context, ArrayList<Photo> photos,
                                                   final RecogniteCallback callback){
        callback.onFailed(photos,"");
        String kindyStr = context.getString(R.string.ev_kindly_prompt);
        SingleConfirmDialogHelper.showConfirmDialog(context,kindyStr,"该图片未识别出文本！",
                "我知道了",
                new SingleConfirmDialogHelper.ConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        callback.onSuccess(photos);
                    }
                });
    }
}
